﻿using FPSO.Models.Constant;
using FPSO.Models.Domain;
using FPSO.Models.ViewModel.Controls;
using FPSO.Services;
using FPSO.Services.Impl;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shell;

namespace FPSO.HMI.Views.Dialog
{
	/// <summary>
	/// TaskEditView.xaml 的交互逻辑
	/// </summary>
	public partial class TaskEditView : Window
    {
        private ITankTaskService TaskService;
		private int taskQueueId;

		private List<ManualCalcResult> calcResults;
        //static TaskShipDataViewModel shipData;
		static TaskTanksDataViewModel tanksData;

		public TaskEditView(int queueId, ITankTaskService taskService)
        {
            InitializeComponent();
            TaskService = taskService;
            taskQueueId = queueId;

			List<TankTask> taskList = TaskService.GetWaitAndExecingCheckingTaskList(taskQueueId);
			//计算每个任务的开始时间
			if (null != taskList)
			{
				//DEBUG 此处表格应显示当前已新建待执行的任务
				List<ManualCalcResult> shipCalcStates = new List<ManualCalcResult>();
				SafeLoadAlgorithmService safeloadAlgorithm = SafeLoadAlgorithmService.GetInstance();
				foreach (TankTask tankTask in taskList)
				{
					Dictionary<string, double> volmDic = new Dictionary<string, double>();
					volmDic.Add(tankTask.TankId, tankTask.TargetVolm);
					List<WBTTask> wbtTaskList = tankTask.WBTTaskList;
					foreach (WBTTask wBT in wbtTaskList)
					{
						volmDic.Add(wBT.WBTTankId, wBT.TargetVolume);
					}
					ManualCalcResult calcResult = safeloadAlgorithm.CallManualCalc(volmDic, 3);

					shipCalcStates.Add(calcResult);
					//shipCalcStates.Add(calcResult.ShipCalc);
				}

				tanksData = new TaskTanksDataViewModel(shipCalcStates);
				shipDataGrid.DataContext = tanksData;

				taskDic = new Dictionary<int, TankTask>();
				foreach (TankTask task in taskList)
				{
					taskDic.Add(task.TaskId, task);
				}
				BindPreTask();
			}
			else
			{
				MessageBox.Show("获取队列" + taskQueueId + "中等待执行和、正在执行和待审核的任务失败，获取结果为：NULL");
				this.Close();
			}
		}

		private Dictionary<int, TankTask> taskDic;
        private void BindPreTask()
        {
            //cmbPreTask.Items.Clear();
            //HashSet<int> preTaskSet = new HashSet<int>();
            //foreach (TankTask task in taskDic.Values)
            //{
            //    if (task.PreTaskId != 0)
            //    {
            //        preTaskSet.Add(task.PreTaskId);
            //    }
            //}
            //foreach (TankTask task in taskDic.Values)
            //{
            //    //if (preTaskSet.Contains(task.TaskId))
            //    {
            //        ComboBoxItem item = new ComboBoxItem();
            //        item.Content = task.PlanStartTime.ToString("HH:mm") + " " + TankConstant.GetTankName(task.TankId);
            //        item.Tag = task.TaskId;
            //        cmbPreTask.Items.Add(item);
            //    }
            //}
        }

        private void ShowErrorMsg(string text)
        {
            MessageBox.Show(text, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        public void InitTaskConent(TankTask tankTask)
        {
            //newTask = tankTask;
            //taskQueueId = 1;
            //SetTaskType(tankTask.TaskType);
            //sourceTank.TankId = tankTask.TankId;
            //txbCurVolume.Text = tankTask.InitVolm.ToString();
            //txbTargetVolume.Text = tankTask.TargetVolm.ToString();
            //txbPipeSpeed.Text = tankTask.PipeSpeed.ToString();

            //if (tankTask.StartType == TaskStartTypeConstant.START_BY_QUEUE_ID)
            //{
            //    QueueChecked(true, false);
            //    SetPreTask(tankTask.PreTaskId);
            //}
            //else
            //{
            //    QueueChecked(false, true);
            //    ucStartTime.Value = tankTask.PlanStartTime;
            //    txbEndTime.Text = tankTask.PlanEndTime.ToString("yyyy-MM-dd HH:mm:ss");

            //    //ucStartTime_OnDateTimeChanged(ucStartTime.Value);
            //}

            //wTaskList = tankTask.WBTTaskList;
            //ShowWBTTaskList();
        }

        private void SetPreTask(int taskId)
        {
            //for (int i = 0; i < cmbPreTask.Items.Count; i++)
            //{
            //    ComboBoxItem item = (ComboBoxItem)cmbPreTask.Items[i];
            //    if (Convert.ToInt32(item.Tag) == taskId)
            //    {
            //        cmbPreTask.SelectedItem = item;
            //        break;
            //    }
            //}

            //PreTask_Changed(null, null);
        }

        private void QueueChecked(bool bQueue, bool bCheck)
        {
            //rbtnStartForQueue.IsChecked = bQueue;
            //rbtnStartForTime.IsChecked = bCheck;
            //StartType_Changed(null, null);
        }

        //测试任务合理性
        private bool CheckTaskRule()
        {
            //SafeLoadAlgorithmService safeloadAlgorithm = SafeLoadAlgorithmService.GetInstance();
            //TaskTankCalcService taskTankCalcService = new TaskTankCalcService(new DBTankTaskService());
            //List<Dictionary<string, double>> tankDic_stags = taskTankCalcService.GetAllTankVolume(newTask);
            ////Dictionary<string, double> tankDic = taskTankCalcService.GetAllTankVolume(newTask);

            //List<ManualCalcResult> results = new List<ManualCalcResult>();
            //List<ShipCalcState> states = new List<ShipCalcState>();
            //foreach (Dictionary<string, double> tankDic in tankDic_stags)
            //{
            //    ManualCalcResult result = safeloadAlgorithm.CallManualCalc(tankDic, 3);
            //    if (result != null)
            //    {
            //        results.Add(result);
            //        ShipCalcState shipCalc = result.ShipCalc;
            //        // 添加结果
            //        states.Add(result.ShipCalc);
            //        double gm = shipCalc.GM;
            //        double trim = shipCalc.Trim;
            //        double heel = shipCalc.Heel;
            //        double maxpermsf = shipCalc.MaxPersf;
            //        double maxpermbm = shipCalc.MaxPerbm;

            //        //DEBUG 这里暂时用简单的判断
            //        // 判断先去掉，不然必返回false导致校核终止
            //        //if (maxpermsf < 100 && maxpermbm < 100)
            //        //{
            //        //    return false;
            //        //}
            //    }
            //}
            //// 赋值
            //shipData.ShipCalcStates = states;
            //shipDataGrid.Items.Refresh();
            return true;
        }

        //这里做分解，根据不同任务线做不同的处理
        private void Confirm_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            //    if (bTaskCheck == false)
            //    {
            //        //如果newTask存在，且当前的方案为待确认或者待执行状态(TaskState = CHECK_ID || WATING_ID)，则为修改当前的方案，需要先修正整个任务时间轴
            //        //DEBUG 编辑状态下仅允许修改流速、目标装载率和压载舱状态，这会导致时间轴的变化
            //        if (newTask != null && (newTask.TaskType == TaskStateConstant.CHECK_ID || newTask.TaskType == TaskStateConstant.WATING_ID))
            //        {
            //            double pipeSpeed;
            //            double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
            //            if (pipeSpeed <= 0 && wTaskList.Count <= 0)
            //            {
            //                throw new Exception("请输入正确的装卸速度!");
            //            }
            //            int targetVolume;
            //            int.TryParse(txbTargetVolume.Text, out targetVolume);
            //            if ((targetVolume < 0 || targetVolume > 100) && wTaskList.Count <= 0)
            //            {
            //                throw new Exception("请输入正确的目标容量!");
            //            }
            //            newTask.PipeSpeed = pipeSpeed;
            //            newTask.TaskState = TaskStateConstant.CHECK_ID;
            //            newTask.TaskResult = TaskResultConstant.UNEXEC_ID;
            //            newTask.WBTTaskList = wTaskList;
            //            double taskHours = CalcEndTime();
            //            newTask.PlanEndTime = newTask.PlanStartTime.AddHours(taskHours);
            //            newTask.UpdateTime = DateTime.Now;

            //            List<TankTask> followTaskList = TaskService.GetWaitAndCheckingTaskListByTaskId(newTask.TaskId);
            //            foreach (TankTask tankTask in followTaskList)
            //            {
            //                TankTask preTask = taskDic[tankTask.PreTaskId];
            //                tankTask.StartType = TaskStartTypeConstant.START_BY_QUEUE_ID;
            //                tankTask.PlanStartTime = preTask.PlanEndTime;
            //                if (preTask.TaskId == newTask.TaskId)
            //                    tankTask.PlanStartTime = newTask.PlanEndTime;

            //                double taskHours0 = CalcEndTime(tankTask);

            //                tankTask.PlanEndTime = tankTask.PlanStartTime.AddHours(taskHours0);
            //                TaskService.UpdateTask(tankTask);
            //                taskDic[tankTask.TaskId] = tankTask;
            //            }

            //            //任务添加调用服务计算所有任务相关舱室液位变化情况
            //            TaskTankCalcService taskTankCalcService = new TaskTankCalcService(TaskService);
            //            List<TaskTankTimeFlagDetail> res = taskTankCalcService.GetAllTaskTankDetails(null);

            //            //TaskService.UpdateTask(newTask);
            //        }
            //        else
            //        {
            //            if (taskQueueId == 2)
            //                Confirm_inQueue2();
            //            else if (taskQueueId == 3)
            //                Confirm_inQueue3();
            //            else
            //                Confirm_inQueue1();
            //        }
            //        if (CheckTaskRule())
            //        {
            //            btn_ok.Content = "确定";
            //            bTaskCheck = true;
            //        }
            //        return;
            //    }
            //    //校核完成并确认后再加入数据库
            //    TaskService.UpdateTask(newTask);
            //    bTaskCheck = false;
            //    this.Close();
            //}
            //catch (Exception ex)
            //{
            //    ShowErrorMsg(ex.Message);
            //}
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Text_Changed(object sender, TextChangedEventArgs e)
        {
            try
            {
                // CalcEndTime();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        //默认经过该方法重新计算的TankTask都是装载过程
        private double CalcEndTime(TankTask localTankTask)
        {
            //if (double.IsNaN(localTankTask.InitVolm) || double.IsNaN(localTankTask.TargetVolm) || double.IsNaN(localTankTask.PipeSpeed))
            //{
            //    return 0;
            //}
            //DateTime startTime = DateTime.MinValue;
            //if (localTankTask.StartType == 1)
            //{
            //    startTime = ucStartTime.Value;
            //}
            //else if (localTankTask.StartType == 2)
            //{
            //    int preTaskId = localTankTask.PreTaskId;
            //    TankTask preTask = taskDic[preTaskId];
            //    startTime = preTask.PlanEndTime;
            //}

            //if (!(localTankTask.PipeSpeed <= 0 || localTankTask.TargetVolm < 0 || localTankTask.TargetVolm > 100 || startTime == DateTime.MinValue || localTankTask.TankId == ""))
            //{
            //    do
            //    {
            //        //DEBUG 后面这部分这样处理的目的是什么？
            //        double currentVolum = GetSourceTankTargetVolume(localTankTask.TankId, localTankTask.InitVolm);
            //        double totalVolum = TankConstant.GetTankVolume(localTankTask.TankId);
            //        double taskVolum = (localTankTask.TargetVolm * 0.01 * totalVolum) - currentVolum;
            //        double taskHours = 0;
            //        if (Math.Abs(taskVolum) > 1)
            //        {
            //            int taskType = GetTaskType();
            //            if (taskType == TaskTypeConstant.LOAD_ID)
            //            {
            //                if (taskVolum < -1.0)
            //                {
            //                    throw new Exception("目标容量小于或等于当前容量,数据不合法!");
            //                }
            //            }
            //            else
            //            {
            //                if (taskVolum > 1.0)
            //                {
            //                    throw new Exception("目标容量大于或等于当前容量,数据不合法!");
            //                }
            //            }
            //            taskHours = Math.Abs(taskVolum) / localTankTask.PipeSpeed;
            //        }

            //        if (taskHours > 36 && localTankTask.WBTTaskList.Count <= 0)
            //        {
            //            throw new Exception("任务时间过长，执行时间超过36小时");
            //        }
            //        if (taskHours < 2 && localTankTask.WBTTaskList.Count <= 0)
            //        {
            //            throw new Exception("任务时间太短，执行时间少于2小时");
            //        }

            //        return taskHours;
            //    }
            //    while (false);
            //}
            return 0;
        }
        private double CalcEndTime()
        {
            //DateTime startTime = DateTime.MinValue;

            //if (string.IsNullOrEmpty(txbPipeSpeed.Text) || string.IsNullOrEmpty(txbTargetVolume.Text))
            //{
            //    txbEndTime.Text = "";
            //    return 0;
            //}

            //double pipeSpeed;
            //double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
            //double targetVolum;
            //double.TryParse(txbTargetVolume.Text, out targetVolum);

            //if ((bool)rbtnStartForTime.IsChecked)
            //{
            //    startTime = ucStartTime.Value;
            //}
            //else if (cmbPreTask.SelectedItem != null)
            //{
            //    int preTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
            //    TankTask preTask = taskDic[preTaskId];
            //    startTime = preTask.PlanEndTime;
            //}

            //if (!(pipeSpeed <= 0 || targetVolum < 0 || targetVolum > 100 || startTime == DateTime.MinValue || sourceTank.TankId == ""))
            //{
            //    do
            //    {
            //        //DEBUG 后面这部分这样处理的目的是什么？
            //        double currentVolum = GetSourceTankCurrentVolume(sourceTank.TankId);
            //        if (newTask != null)
            //            currentVolum = GetSourceTankTargetVolume(sourceTank.TankId, newTask.InitVolm);
            //        double totalVolum = TankConstant.GetTankVolume(sourceTank.TankId);
            //        double taskVolum = (targetVolum * 0.01 * totalVolum) - currentVolum;
            //        double taskHours = 0;
            //        if (Math.Abs(taskVolum) > 1)
            //        {
            //            int taskType = GetTaskType();
            //            if (taskType == TaskTypeConstant.LOAD_ID)
            //            {
            //                if (taskVolum < -1.0)
            //                {
            //                    throw new Exception("目标容量小于或等于当前容量,数据不合法!");
            //                }
            //            }
            //            else
            //            {
            //                if (taskVolum > 1.0)
            //                {
            //                    throw new Exception("目标容量大于或等于当前容量,数据不合法!");
            //                }
            //            }
            //            taskHours = Math.Abs(taskVolum) / pipeSpeed;
            //        }

            //        if (taskHours > 36 && wTaskList.Count <= 0)
            //        {
            //            throw new Exception("任务时间过长，执行时间超过36小时");
            //        }
            //        if (taskHours < 2 && wTaskList.Count <= 0)
            //        {
            //            throw new Exception("任务时间太短，执行时间少于2小时");
            //        }

            //        txbEndTime.Text = startTime.AddHours(taskHours).ToString("yyyy-MM-dd HH:mm:ss");

            //        return taskHours;
            //    }
            //    while (false);
            //}

            //txbEndTime.Text = "";
            return 0;
        }

        private double GetSourceTankCurrentVolume(string tankId)
        {
			//获取当前选择舱室的容量
			//TankOilViewModel tankOilViewModel = oilViewModel.GetCotViewModel(tankId);
			//double totalVolum = tankOilViewModel.TotalVolume;
			//double currentVolum = tankOilViewModel.Volume;
			//TankTask lastSourceTask = waitTaskList.Where(t => t.SwapTargetTank1 == sourceTank.TankId).LastOrDefault();
			//TankTask lastTargetTask = waitTaskList.Where(t => t.TankId == sourceTank.TankId).LastOrDefault();
			//if (lastSourceTask != null)
			//{
			//    currentVolum = lastSourceTask.TargetVolm * 0.01 * totalVolum;
			//}

			//if (lastTargetTask != null)
			//{
			//    if (lastSourceTask == null || lastTargetTask.PlanStartTime > lastSourceTask.PlanStartTime)
			//    {
			//        currentVolum += lastTargetTask.PipeSpeed * (lastTargetTask.PlanEndTime - lastTargetTask.PlanStartTime).TotalHours;
			//    }
			//}
			//return currentVolum;
			return 0;
        }
        private double GetSourceTankTargetVolume(string tankId, double volume)
        {
			//获取当前选择舱室的容量
			//TankOilViewModel tankOilViewModel = oilViewModel.GetCotViewModel(tankId);
			//double totalVolum = tankOilViewModel.TotalVolume;
			//double currentVolum = volume * 0.01 * totalVolum;
			//return currentVolum;
			return 0;
        }
        private void ucStartTime_OnDateTimeChanged(DateTime obj)
        {
            try
            {
                CalcEndTime();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        private void UpdateTankTask(TankTask oriTankTask, TankTask importTankTask)
        {

        }

		public static readonly DependencyProperty DialogTitleProperty =
	DependencyProperty.Register("DialogTitle", typeof(string), typeof(TaskEditView), new PropertyMetadata("添加任务"));
		public string DialogTitle
		{
			get { return (string)GetValue(DialogTitleProperty); }
			set { SetValue(DialogTitleProperty, value); }
		}

		private void WindowMove(object sender, MouseEventArgs e)
		{
			if (e.LeftButton == MouseButtonState.Pressed)
			{
				DragMove();
			}
		}
	}
}
